<template>
  <el-dialog
    v-model="visible"
    title="误报统计分析"
    width="900px"
    destroy-on-close
    :before-close="handleClose"
    :fullscreen="isFullscreen"
  >
    <div v-loading="loading" class="analysis-container">
      <!-- 时间范围选择 -->
      <el-card class="analysis-card time-range-card">
        <div class="time-range-controls">
          <el-select
            v-model="timeRange"
            placeholder="时间范围"
            @change="handleTimeRangeChange"
            class="time-select"
          >
            <el-option label="最近7天" value="7d"></el-option>
            <el-option label="最近30天" value="30d"></el-option>
            <el-option label="最近90天" value="90d"></el-option>
            <el-option label="自定义时间段" value="custom"></el-option>
          </el-select>

          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            v-if="timeRange === 'custom'"
            class="date-picker"
          />

          <el-button
            type="default"
            icon="Download"
            size="small"
            @click="handleExportReport"
            class="export-btn"
          >
            导出报表
          </el-button>

          <el-button
            type="default"
            icon="Refresh"
            size="small"
            @click="fetchAnalysisData"
            class="refresh-btn"
          >
            刷新
          </el-button>

          <el-button
            type="text"
            icon="Fullscreen"
            size="small"
            @click="isFullscreen = !isFullscreen"
            class="fullscreen-btn"
          />
        </div>
      </el-card>

      <!-- 误报趋势图 -->
      <el-card class="analysis-card">
        <template #header>
          <span class="card-title">误报趋势图</span>
        </template>
        <div class="chart-container">
          <el-chart :auto-resize="true">
            <el-line-series
              :data="trendData"
              x-field="date"
              y-field="count"
              point-size="6"
              point-shape="circle"
              line-style="solid"
              :line-width="2"
            />
            <el-axis-x />
            <el-axis-y />
            <el-tooltip formatter="日期: {x}<br/>数量: {y}" position="top" />
          </el-chart>
        </div>
      </el-card>

      <!-- 误报类型分布 -->
      <el-card class="analysis-card">
        <template #header>
          <span class="card-title">误报类型分布</span>
        </template>
        <div class="distribution-container">
          <div class="chart-wrapper">
            <el-chart :auto-resize="true" class="pie-chart">
              <el-pie-series
                :data="typeDistributionData"
                category-field="name"
                value-field="value"
                radius="70%"
                label-position="outside"
                :label-style="{ fontSize: '12px' }"
              />
              <el-tooltip formatter="{name}: {value}条 ({percentage}%)" />
            </el-chart>
          </div>
          <div class="distribution-list">
            <div
              v-for="(item, index) in typeDistributionData"
              :key="index"
              class="distribution-item"
              :style="{ '--color': item.color }"
            >
              <div class="item-color"></div>
              <div class="item-name">{{ item.name }}</div>
              <div class="item-value">
                {{ item.value }}条 ({{ item.percentage }}%)
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- TOP误报原因 -->
      <el-card class="analysis-card">
        <template #header>
          <span class="card-title">TOP误报原因</span>
        </template>
        <div class="reason-container">
          <div
            v-for="(item, index) in topReasonsData"
            :key="index"
            class="reason-item"
            :style="{ width: `${item.percentage}%` }"
          >
            <div class="reason-rank">{{ index + 1 }}.</div>
            <div class="reason-name">{{ item.name }}</div>
            <div class="reason-bar">
              <div
                class="reason-progress"
                :style="{
                  width: `${item.percentage}%`,
                  backgroundColor: item.color,
                }"
              ></div>
            </div>
            <div class="reason-value">
              {{ item.count }} ({{ item.percentage }}%)
            </div>
          </div>
        </div>
      </el-card>

      <!-- TOP误报资产 -->
      <el-card class="analysis-card">
        <template #header>
          <span class="card-title">TOP误报资产</span>
        </template>
        <el-table :data="topAssetsData" border row-key="assetIp">
          <el-table-column
            prop="rank"
            label="序号"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="assetIp"
            label="资产IP"
            min-width="120"
          ></el-table-column>
          <el-table-column
            prop="count"
            label="次数"
            min-width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="percentage"
            label="占比"
            min-width="100"
            align="center"
          >
            <template #default="scope"> {{ scope.row.percentage }}% </template>
          </el-table-column>
          <el-table-column
            prop="mainType"
            label="主要类型"
            min-width="150"
          ></el-table-column>
        </el-table>
      </el-card>

      <!-- 处理效率统计 -->
      <el-card class="analysis-card">
        <template #header>
          <span class="card-title">处理效率统计</span>
        </template>
        <div class="efficiency-grid">
          <div class="efficiency-item">
            <div class="item-label">平均处理时长:</div>
            <div class="item-value">
              {{ efficiencyData.avgProcessTime || "0" }} 小时
            </div>
          </div>
          <div class="efficiency-item">
            <div class="item-label">当日处理率:</div>
            <div class="item-value">
              {{ efficiencyData.dailyProcessRate || "0" }}%
            </div>
          </div>
          <div class="efficiency-item">
            <div class="item-label">待处理积压:</div>
            <div class="item-value">
              {{ efficiencyData.pendingCount || "0" }} 条
            </div>
            <div class="item-desc">
              (最早{{ efficiencyData.oldestPendingTime || "0" }}天前)
            </div>
          </div>
          <div class="efficiency-item">
            <div class="item-label">自动化处理率:</div>
            <div class="item-value">
              {{ efficiencyData.autoProcessRate || "0" }}%
            </div>
            <div class="item-desc">(通过白名单自动处理)</div>
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
// import { getFalsePositiveAnalysis } from "@/api/falsePositive";

// 定义属性和事件
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue"]);

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const isFullscreen = ref(false);
const timeRange = ref("7d");
const dateRange = ref([]);

// 分析数据
const trendData = ref([]);
const typeDistributionData = ref([]);
const topReasonsData = ref([]);
const topAssetsData = ref([]);
const efficiencyData = ref({});

// 监听显示状态变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val) {
      fetchAnalysisData();
    }
  }
);

// 时间范围变化
const handleTimeRangeChange = () => {
  if (timeRange.value !== "custom") {
    fetchAnalysisData();
  }
};

// 获取分析数据
const fetchAnalysisData = async () => {
  // loading.value = true;
  // try {
  //   const params = {
  //     timeRange: timeRange.value,
  //     startDate: dateRange.value[0] ? formatDate(dateRange.value[0]) : "",
  //     endDate: dateRange.value[1] ? formatDate(dateRange.value[1]) : "",
  //   };
  //   const { data } = await getFalsePositiveAnalysis(params);
  //   // 填充趋势图数据
  //   trendData.value = data.trend || [];
  //   // 填充类型分布数据
  //   const typeColors = ["#1890ff", "#52c41a", "#faad14", "#f5222d", "#722ed1"];
  //   typeDistributionData.value = (data.typeDistribution || []).map(
  //     (item, index) => ({
  //       ...item,
  //       color: typeColors[index % typeColors.length],
  //     })
  //   );
  //   // 填充TOP原因数据
  //   const reasonColors = [
  //     "#1890ff",
  //     "#40a9ff",
  //     "#69b1ff",
  //     "#91c7ff",
  //     "#b8ddff",
  //     "#e0efff",
  //   ];
  //   topReasonsData.value = (data.topReasons || []).map((item, index) => ({
  //     ...item,
  //     color: reasonColors[index % reasonColors.length],
  //   }));
  //   // 填充TOP资产数据
  //   topAssetsData.value = (data.topAssets || []).map((item, index) => ({
  //     ...item,
  //     rank: index + 1,
  //   }));
  //   // 填充效率数据
  //   efficiencyData.value = data.efficiency || {};
  // } catch (error) {
  //   ElMessage.error("获取分析数据失败");
  // } finally {
  //   loading.value = false;
  // }
};

// 导出报表
const handleExportReport = () => {
  ElMessage.success("报表导出成功");
};

// 关闭对话框
const handleClose = () => {
  emit("update:modelValue", false);
};

// 辅助函数：格式化日期
const formatDate = (date) => {
  if (!(date instanceof Date)) return "";
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};
</script>

<style scoped lang="scss">
.analysis-container {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.analysis-card {
  margin-bottom: 15px;
  border-radius: 6px;
}

.card-title {
  font-weight: 500;
  color: #1d2129;
}

.time-range-card {
  border: none;
  background: transparent;
  box-shadow: none;
  margin-bottom: 10px;
}

.time-range-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.time-select {
  width: 140px;
}

.date-picker {
  width: 300px;
}

.export-btn,
.refresh-btn {
  margin-left: auto;
}

.fullscreen-btn {
  margin-left: 10px;
}

.chart-container {
  height: 300px;
  margin-top: 10px;
}

.distribution-container {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.chart-wrapper {
  flex: 1;
  height: 250px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.distribution-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 15px;
}

.distribution-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.item-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: var(--color);
}

.item-name {
  width: 100px;
  font-weight: 500;
}

.item-value {
  flex: 1;
  color: #666;
}

.reason-container {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.reason-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding-right: 100px;
  position: relative;
}

.reason-rank {
  width: 30px;
  text-align: right;
  font-weight: 500;
}

.reason-name {
  width: 120px;
  font-weight: 500;
}

.reason-bar {
  flex: 1;
  height: 10px;
  background-color: #f0f0f0;
  border-radius: 5px;
  overflow: hidden;
}

.reason-progress {
  height: 100%;
  border-radius: 5px;
  transition: width 0.5s ease;
}

.reason-value {
  position: absolute;
  right: 0;
  width: 100px;
  text-align: right;
  color: #666;
}

.efficiency-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 10px;
}

.efficiency-item {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.item-label {
  color: #86909c;
  font-size: 13px;
  margin-bottom: 5px;
}

.item-value {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 3px;
}

.item-desc {
  color: #86909c;
  font-size: 12px;
}
</style>
